from django.forms import models
from django.http import JsonResponse,HttpResponse

from .models import BookinfoModels
from django.shortcuts import render

# Create your views here.
from django.views import View
import json


class BookInfoView(View):
    # 获取书籍
    def get(self,request):
        # 1、获取所有书籍
        books = BookinfoModels.objects.all()
        # 数据转换
        book_list = []
        for book in books:
            book_dict = {
                "id":book.id,
                "btitle":book.btitle,
                "bpub_date":book.bpub_date,
                "bread":book.bread,
                "bcomment":book.bcomment
            }
            book_list.append(book_dict)
         # 返回响应
        return JsonResponse(book_list,safe=False)

    # 新建书籍
    def post(self,request):
        # 1、获取参数
        res = json.loads(request.body.decode())
        print("res:",res)
        btitle = res.get('btitle'),
        bpub_date = res.get('bpub_date'),
        bread = res.get('bread'),
        bcomment = res.get('bcomment')
        # 2、校验参数

        # 3、数据入库
        book = BookinfoModels.objects.create(**res)
        # 4、返回响应
        book_dict = {
            "id": book.id,
            "btitle": book.btitle,
            "bpub_date": book.bpub_date,
            "bread": book.bread,
            "bcomment": book.bcomment
        }
        return JsonResponse(book_dict,status=201)


class BookInfoDetailView(View):
    # 获取单个数据
    def get(self,request,pk):
        # 1、通过pk获取单本书籍
        book = BookinfoModels.objects.get(pk = pk)
        # 2、数据转换
        book_dict = {
            "id": book.id,
            "btitle": book.btitle,
            "bpub_date": book.bpub_date,
            "bread": book.bread,
            "bcomment": book.bcomment
        }
        # 3、返回数据
        return JsonResponse(book_dict)

    # 修改书籍
    def put(self,request,pk):
        # 1、获取更改后的数据
        dict_data = json.loads(request.body.decode())

        # 2、校验参数
        # 3、数据入库
        BookinfoModels.objects.filter(pk = pk).update(**dict_data)
        book = BookinfoModels.objects.get(pk=pk)
        # 4、数据转换
        book_dict = {
            "id": book.id,
            "btitle": book.btitle,
            "bpub_date": book.bpub_date,
            "bread": book.bread,
            "bcomment": book.bcomment
        }

        # 5、返回数据
        return JsonResponse(book_dict)

    # 删除书籍
    def delete(self,request,pk):
        # 1、获取书籍
        book = BookinfoModels.objects.get(id = pk)
        # 2、删除书籍
        book.delete()
        # 3、返回数据
        return HttpResponse(status=204)
